<?php
	require('../Model/mysql.php');
	require('../host_config.php');
	$mysql = new MySQL();
	$link = $mysql->connect($mysql_host, $mysql_user, $mysql_passwd, $mysql_db);
	if(isset($_POST['imsi']))
	{
		$imsi = $mysql->real($_POST["imsi"]);
		$sql = "SELECT `shopid`, `flag` FROM `Client` WHERE `imsi` = '$imsi'";
		$result = $mysql->query($sql, $link);
		if($result) {
			while($row = mysql_fetch_row($result)) {
				$shopid = $row[0];
				$flag = $row[1];
				if($flag == '0') {		//有位置
					$return[] = array(
							'shopid' => $shopid,
							'time' => '10',
							'flag' => $flag
							);
				}else if($flag == '-1') {		//要排隊
					//$sql = "Select `arrivetime`, `leavetime`, from `Statistics` WHERE `shopid` = '$shopid'";
					$sql = "SELECT `arrivetime`, `leavetime` FROM `Statistics` WHERE `shopid` = '$shopid' ORDER BY leavetime DESC limit 5";
					$rel = $mysql->query($sql, $link);
					$count = 0;
					while($row = mysql_fetch_row($rel)) {
						$eatTime += strtotime($row[1]) - strtotime($row[0]);
						$count++;
					}
					$eatTime /= $count;
					$return[] = array(
							'shopid' => $shopid,
							'time' => $eatTime,
							'flag' => $flag
							);
				}else {		// 用餐中
					$return[] = array(
							'shopid' => $shopid,
							'time' => '0',
							'flag' => $flag
							);
				}
			}

			if($row === FALSE) {
				if(count($return) == 0) {
					$sql = "SELECT `shopid` FROM `Statistics` WHERE `imsi` = '$imsi' ORDER BY leavetime DESC limit 1";
					$rel = $mysql->query($sql, $link);
					$row = mysql_fetch_row($rel);
					$shopid = $row[0];
					$return[] = array(
							'shopid' => $shopid,
							'time' => '-2',
							'flag' => '-2'
					);
				}
			}

			print(json_encode($return));
		}

	}else {
		echo "<script language='javascript'>";
		echo "alert('You have no permission to read this page!');";
		echo "history.back();";
		echo "</script>";
		header("location:../login.php");
	}
?>
